# -*- coding:utf-8 -*-
'''import socket
import select
from threading import Thread'''

import gevent
from gevent import socket,select
from gevent.server import StreamServer

class Request(object):
    def __init__(self,request):
        self.request    = request
        self.host       = None
        self.port       = 80
        self.method     = 'GET'
        self.uri        = '/'
        self.lenth      = len(self.request)
        self.protocol   = 'HTTP/1.1'
        self.headers    = {}
        self.content    = None
        try:self.parse()
        except:pass

    def parse(self):
        head,self.content = self.request.split('\r\n\r\n')
        lines = head.split('\r\n')
        '''解析请求方法和uri'''
        self.method,self.uri,self.protocol = lines[0].split()
        self.method = self.method.upper()

        '''解析其他header'''
        for line in lines[1:]:
            head = line.split(':')
            self.headers[head[0]] = ':'.join(head[1:]).strip()

        '''处理目标主机和端口'''
        host_port = self.headers['Host'].split(':')
        self.host = host_port[0]
        if len(host_port)==2:
            self.port = int(host_port[1])

class Response(object):
    def __init__(self,response):
        self.response   = response
        self.lenth      = len(self.response)
        self.protocol   = 'HTTP/1.1'
        self.status     = 200
        self.message    = ''
        self.mimetype   = ''
        self.headers    = {}
        self.content    = None

    def parse(self):
        head,self.content = self.response.split('\r\n\r\n')
        lines = head.split('\r\n')
        '''解析返回状态'''
        line = lines[0].split(' ')
        self.httptype = line[0]
        self.status = int(line[1])
        self.message = line[2]
        '''解析其他header'''
        for line in lines[1:]:
            line= lines[i].split(':')
            key = line.pop(0)
            value = ''.join(line)
            self.headers[key] = value.strip()
        self.mimetype = self.headers['Content-Type']


class HttpTunnel(object):
    BUFFER = 8192
    def __init__(self,client,addr):
        self.addr   = addr
        self.client = client
        while True:
            buff = self.client.recv(self.BUFFER)
            print(buff)
            if not buff:
                print(1111)
                break
            req = Request(buff)
            if req.host and req.port:
                sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
                sock.connect((req.host,req.port))
            sock.send(buff)
            tunnels = []
            if req.method == 'CONNECT':
                tunnels.append(gevent.spawn(self.dotunnel,self.client,sock,False))
                tunnels.append(gevent.spawn(self.dotunnel,sock,self.client,True))
            else:
                tunnels.append(gevent.spawn(self.dotunnel,sock,self.client,True))
            gevent.joinall(tunnels)
        self.client.close()

    def dotunnel(self,recver,sender,rd=False):
        try:
            while True:
                buff = recver.recv(self.BUFFER)
                sender.send(buff)
                if not buff:break
        except:
            #recver.close()
            #sender.close()
            return
        if rd:
            recver.close()
            sender.close()

def Proxy(h='127.0.0.1',p=6666):
    p=StreamServer((h,p),HttpTunnel)
    p.start()
    print('start processes: ok')
    p.serve_forever()

Proxy()
